If statements can be nested together. That means we could have one inside another. Consider the next code fragment -

  1. if (a>b){
    1. if (a>c){
    2. System.out.println("A bigest");
    3. } else {
    4. System.out.println("C biggest");
    5. }
  2. } else {
    1. if (b>c){
    2. System.out.println("B biggest");
    3. } else {
    4. System.out.println("C biggest");
    5. }
  3. }

This code is checking to see what is the biggest number out of three. A, B and C.

Ok this is a bit more complicated but fear not! If you look at the first IF statement it says A>B. So for this to be true A will HAVE TO be bigger than B. Inside it's true block we have another condition saying A>C. As we already know A is bigger than B we only need to compare to C as comparing C to B is pointless (as we already know A is bigger). Look at the diagram below -

If A > B is true then we know A > B. Or more importantly we know that B CAN NOT be the biggest. That is why the whole left hand side of the tree above does not consider B. On the right hand side we are only concerned with B as we have already shown then B is bigger than A as A > B is false.

The T and F stand for true and false. If a expression is true then we do one thing if false another. This kind of diagram is known as a truth tree and can help in making complex decisions using if statements.

next creating a truth tree >>

 

 
Basics
Menu
Search